package com;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;

public class MainClientThread extends PublicThread {

	private boolean isConnect = false;
	private ServerThread server = null;
	private String address = "";
	private int port = 0;

	public MainClientThread(ServerSocket serverSocket, ThreadPool pool, String add, int port) {
		this.serverSocket = serverSocket;
		this.threadPool = pool;
		this.address = add;
		this.port = port;
		addToThreadPool();
	}

	public void run() {
		InputStream in = null;
		byte[] data = new byte[4096];
		int lenght = 0;
		try {
			while (isRun) {
				System.out.println("Waiting MainClient Connect, Port: " + serverSocket.getLocalPort());
				socket = serverSocket.accept();
				System.out.println("new MainClient Connect, Address: " + socket.getInetAddress().getHostAddress()
						+ ", Port: " + socket.getPort());
				send(("Info Address " + address + " Port " + port).getBytes());
				isConnect = true;
				try {
					in = socket.getInputStream();
					while (isRun && lenght > -1) {
						lenght = in.read(data);
						if (lenght > 0)
							System.out.println(new String(data, 0, lenght));
						sleep(10);
					}
					System.out.println("Remote Close MainClient, Address: " + socket.getInetAddress().getHostAddress()
							+ ", Port: " + socket.getPort());
				} catch (IOException e) {
					System.out.println("ServerThread Error " + e.getMessage());
				}
				socket = null;
				sleep(10);
			}
		} catch (IOException e) {
			System.out.println("ServerThread Error " + e.getMessage());
		}

		isConnect = false;
		close();
		removeFromThreadPool();
	}

	public void close() {
		synchronized (this) {
			try {
				super.closeThread();
			} catch (Exception e1) {
				System.out.print("close MainClinetThread socket Error, Port:" + serverSocket.getLocalPort());
			}
		}
	}

	public void serServer(ServerThread server) {
		this.server = server;
	}

	public boolean isConnect() {
		return this.isConnect;
	}

	public void send(byte[] data, int s, int l) {
		synchronized (this) {
			if (socket != null) {
				try {
					socket.getOutputStream().write(data, s, l);
				} catch (IOException e) {
					System.out.println(e.getMessage() + "MainClinetThread Send Data Error, Address: "
							+ socket.getInetAddress().getHostAddress() + ", Port: " + socket.getPort());
				}
			}
		}
	}

	public void send(byte[] bytes) {
		send(bytes, 0, bytes.length);
	}

}
